﻿using CIS.Web.Common;
using CIS.Web.Models;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("ProfilePayment")]
	public class ProfilePaymentController : BaseDbController
	{
		public ActionResult Index()
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName);

			return View();
		}

		public async Task<JsonCamelCaseResult> GetData(int? page, int? rows, string sort, string order, ProfileConferenceAttendPayModel model)
		{
			int take = rows ?? ConstValues.DefaultGridRows;
			int skip = ((page ?? 1) - 1) * take;

			var sql = from profilepaymentrecord in DbContext.ProfilePaymentRecord.AsNoTracking()
					    .Where(x => x.Creator == LoginUser.UserName)
				  join conferenceAttendenceInfo in DbContext.ConferenceAttendenceInfo.AsNoTracking()
				      on profilepaymentrecord.AttendenceId equals conferenceAttendenceInfo.ID
				  join conferenceMaster in DbContext.ConferenceMaster.AsNoTracking()
				      on conferenceAttendenceInfo.ConferenceId equals conferenceMaster.ID

				  select new
				  {
					  ConferenceName = conferenceMaster.ConferenceName,
					  Currency = profilepaymentrecord.Currency,
					  Fee = profilepaymentrecord.Fee,
					  FeeStatus = profilepaymentrecord.FeeStatus,
					  Sort = conferenceMaster.Sort,
					  CreateDate = profilepaymentrecord.CreateDate,
					  ConferenceNickName = conferenceMaster.ConferenceNickName,
					  HomePageUrl = conferenceMaster.HomePageUrl,
					  IsInternational = conferenceMaster.IsInternational,
				  };

			if (!string.IsNullOrWhiteSpace(model.queryConferenceName) && model.queryConferenceName != "")
			{
				sql = sql.Where(x => x.ConferenceName.Contains(model.queryConferenceName));
			}
			if (!string.IsNullOrWhiteSpace(model.queryHasPaid) && model.queryHasPaid != "")
			{
				var paidSql = model.queryHasPaid == ConstValues.PaidStatus.已缴费 ? true : false;
				sql = sql.Where(x => x.FeeStatus == paidSql);
			}

			int total = await sql.CountAsync();
			if (!string.IsNullOrEmpty(sort))
			{
				sql = sql.OrderBy(sort + ConstValues.chrSpace + order).Skip(skip).Take(take);
			}
			else
			{
				sql = sql.OrderByDescending(x => x.CreateDate).Skip(skip).Take(take);
			}

			var sqlResult = await sql.ToListAsync();

			var result = sqlResult.Select(x => new
			{
				ConferenceName = x.ConferenceName,
				Currency = x.Currency,
				Fee = x.Fee.ToString("N2"),
				FeeStatus = x.FeeStatus,
				CreateDate = !x.IsInternational ? x.CreateDate.Value.ToString("yyyy-MM-dd HH:mm") : x.CreateDate.Value.ToString("MM/dd/yyyy HH:mm"),
				ConferenceNickName = x.ConferenceNickName,
				HomePageUrl = x.HomePageUrl
			});

			return JsonCamelCase(new
			{
				Total = total,
				Rows = result,
			},
			JsonRequestBehavior.AllowGet);
		}
	}
}